﻿/***************************************************************************
//* Foxit Software Inc.
//* Copyright(C) 2005-2012, all rights reserved.
//*
//* The following code is copyrighted and contains proprietary information
//* and trade secrets of Foxit Software Inc.                                                      *
***************************************************************************/
//常用对话框;


define(function (require, exports, module) {
    var FXREADER = require('./FXReader.js');
    var _AlertDlgHtml = "",
          _AlertDlg = null,
          _bAlertDlgInited = false,

          _ConfirmDlgHtml = "",
          _ConfirmDlg = null,
          _bComfirmDlgInited = false,

          _ConfirmPasswordDlgHtml = "",
          _bConfirmPasswordDlgInited = false,
          _ConfirmPasswordDlg = null,

          _TextCopyDlgHtml = "",
          _TextCopyDlg = null,
          _bTextCopyDlgInited = false,

          _LoadingHtml = "",
          _LoadingDlg = null,
          _bLoadingDlgInited = false,
          
          _Language = null,
          _DefaultDlgTitle = "";


    function _PopupCopyDlg(text2Copy, title, btntitle, closeProc, width) {
        _Language = FXREADER.AppInstance.GetLanguage();
        _DefaultDlgTitle = _Language.CommonDialog.DefaultDlgTitle;
        if (!_bTextCopyDlgInited) {
            var inputText = "";
            if (FXREADER.Environment.mobile || FXREADER.Environment.iOS)
                inputText = "<textarea id='fxtextcopy_text' class='input' style='width:390px;height:50px;font-size:12px;resize:none;' type='text' value='' />";
            else
                inputText = "<textarea id='fxtextcopy_text' class='input' style='width:390px;height:50px;font-size:12px;resize:none;' type='text' value=''  readonly='readonly'/>";
            _TextCopyDlgHtml = "<div id='fxtextcopy_dialog' class='fwr_dialog fwr_dialog_padding fwr_formEl_a fwr_hidden ui-dialog-content ui-widget-content' style='display: block; width: auto; min-height: 0px; height: auto;'>"
                                                    + "<div style='padding-bottom: 5px;'>"
                                                        + "<span>" + _Language.CommonDialog.TextCopyLimitMsg + "</span>"
                                                    + "</div>"
                                                    + inputText
                                                    + "<div style='height:20px'> </div>"
                                                    + "<div class='fwr_buttons_bar'>"
                                                        + "<button class='fwr_button orange' id='fxtextcopy_closebtn'  type='button'>" + _Language.CommonDialog.DefaultCloseBtnTitle + "</button>"
                                                    + "</div>"
                                                    + "<div class='clear'></div>"
                                            + "</div>";
            var jqTextCopyDlgHtml = $(_TextCopyDlgHtml);
            _TextCopyDlg = jqTextCopyDlgHtml.dialog({
                autoOpen: false,
                modal: true,
                position: 'center',
                width: 430,
                closeText: '',
                title: _DefaultDlgTitle
            });
            $("#fxtextcopy_closebtn").bind("click", function () {
                _TextCopyDlg.dialog('close');
            });
            _bTextCopyDlgInited = true;
        }
        if (!_TextCopyDlg)
            return;
        if (title == "" || title == null) {
            title = _DefaultDlgTitle;
        }
        if (closeProc)
            _TextCopyDlg.dialog({ close: function (event, ui) {
                closeProc(); return false;
            }
            });

        if (width == null)
            _TextCopyDlg.dialog("option", "width", 430);
        else
            _TextCopyDlg.dialog("option", "width", width);

        _TextCopyDlg.dialog("option", "title", title);
        var jqTextLable = $("#fxtextcopy_text");
        jqTextLable.val(text2Copy);

        if (btntitle == null)
            btntitle = _Language.CommonDialog.DefaultCloseBtnTitle;
        $("#fxtextcopy_closebtn").text(btntitle);
        _TextCopyDlg.dialog('open');
        if (FXREADER.Environment.mobile || FXREADER.Environment.iOS)
        {
        	jqTextLable.unbind('touchstart.jsp').bind('touchstart.jsp', function (e) {
                this.setSelectionRange(0, jqTextLable.val().length);
                jqTextLable.focus();
                return false;
             });
        	 jqTextLable.trigger('touchstart.jsp');
        }
        else
        {
        	 jqTextLable.focus();
             jqTextLable.select();
        }
    }

    FXREADER.Waiting = function (settings) {
        _Language = FXREADER.AppInstance.GetLanguage();
        _DefaultDlgTitle = _Language.CommonDialog.DefaultDlgTitle;
        var windowWidth = $(window).width();
        var windowHeight = $(window).height();
        var xScale = windowWidth/1366;
        var yScale = windowHeight/768;
        var scale = xScale>yScale ? yScale : xScale;
        scale = scale > 1.0 ? 1.0 : scale;
        var realWidth = scale*476;
        var realHeight = scale*284;
        if (!_bLoadingDlgInited) {
            _LoadingHtml = "<div id='fxloading_dlg' class='fwr_ajax_loading'></div>";
            var jqLoadingDlgHtml = $(_LoadingHtml);
            _LoadingDlg = jqLoadingDlgHtml.dialog({
                autoOpen: false,
                dialogClass: "fwr_loadingScreen",
                closeOnEscape: false,
                draggable: false,
                resizable: false,
                modal: true,
                position: 'center',
                width: realWidth,
                height: realHeight,
                closeText: '',
                title: _DefaultDlgTitle,
                open: function () {
                    // scrollbar fix for IE
                    $('body').css('overflow', 'hidden');
                    $('.ui-widget-overlay').css('background-color', "#fff");
                },
                beforeClose: function()
                {
                	 $('.ui-widget-overlay').css('background-color', "#000");
                	 $('.ui-widget-overlay').css('z-index', "1003");
                	 $('.fwr_main_frame_wnd').css('z-index', "1001");
                },
                close: function () {
                    // reset overflow
                    $('body').css('overflow', 'auto');
                }
            });
            _LoadingDlg.siblings('.ui-dialog-titlebar').remove();
            _bLoadingDlgInited = true;
        }
        if (!_LoadingDlg)
            return;
        // $("#fxloading_dlg").html(settings.message && '' != settings.message ? settings.message : 'Please wait...');
        _LoadingDlg.dialog('option', 'title', settings.title && '' != settings.title ? settings.title : 'Loading');
        _LoadingDlg.dialog('open');
    };

    FXREADER.CloseWaiting = function () {
        _LoadingDlg && _LoadingDlg.dialog('close');
    };

    /**
     * @description Pupup a Alert dialog.
		* @param {String} title  title of the dialog, if this parameter is null or empty, default title will be use.
		* @param {String} message of the dialog.
		* @param {String} btntitle title of “OK” button, if this parameter is null or empty, default title will be use.
		* @param {Function} closeProc allback of close the dialog, if this parameter is null or empty, FXREADER.EndAlert() will be use by default;
		* @param {Number} width of the dialog，if this parameter is null or empty, 300 will be use by default.
    */
    FXREADER.Alert = function (title, msg, btntitle, closeProc, width,bAutoClose) {
    	if (FXREADER.Environment.mobile || FXREADER.Environment.iOS) {
    		if(!_bAlertDlgInited)
    		{
    			var toolTipDivHtml = "<div id='fwr_mobile_tooltip'></div>";
    			var jqMainFrm = $("#" + FXREADER.AppInstance.GetTopPanelID());
             	jqMainFrm.append(toolTipDivHtml);	
    		}
    		_bAlertDlgInited = true;
    		$('#fwr_mobile_tooltip').tinytooltip({
    			message: function() {
    				return msg;
    			},
    			hover: false
    		});
    		if(bAutoClose==null)
    			bAutoClose = false;
    		$('#fwr_mobile_tooltip').trigger('showtooltip');
    		if(bAutoClose)
    			setTimeout(function(){$('#fwr_mobile_tooltip').trigger('hidetooltip');},FXREADER.Config.TooltipTimeout);
    	}
    	else
    	{
    		_Language = FXREADER.AppInstance.GetLanguage();
            _DefaultDlgTitle = _Language.CommonDialog.DefaultDlgTitle;
            if (!_bAlertDlgInited) {
                _AlertDlgHtml = "<div id='fxalert_dialog' style='display: none; min-height: 30px;'>" +
                                                "<div class='fwr_dialog fwr_dialog_padding fwr_hidden ui-dialog-content ui-widget-content' style='display: block;width: auto; min-height: 60px; height: auto;'>" +
                                                    "<div class='frow'>" +
                                                        "<p id='fxalert_msg'>" +
                                                        "</p>" +
                                                    "</div>" +
                                                "<div class='fwr_buttons_bar' style='clear: both;'>" +
                                                    "<button class='fwr_button orange' id='fxalert_closebtn' name='OK' type='button' >" + _Language.CommonDialog.DefaultOKBtnTitle + "</button>" +
                                                "</div>" +
                                            "</div>" +
                                        "</div>";

                var jqAlertDlgHtml = $(_AlertDlgHtml);
                _AlertDlg = jqAlertDlgHtml.dialog({
                    autoOpen: false,
                    modal: true,
                    position: 'center',
                    width: 300,
                    closeText: '',
                    title: _DefaultDlgTitle
                });
                $("#fxalert_closebtn").bind("click", function () {
                    _AlertDlg.dialog('close');
                });
                _bAlertDlgInited = true;
            }
            if (!_AlertDlg)
                return;
            if (title == "" || title == null) {
                title = _DefaultDlgTitle;
            }
            if (msg == null)
                msg = "";
            if (closeProc)
                _AlertDlg.dialog({ close: function (event, ui) {
                    closeProc(); return false;
                }
                });

            if (width == null)
                _AlertDlg.dialog("option", "width", 300);
            else
                _AlertDlg.dialog("option", "width", width);

            _AlertDlg.dialog("option", "title", title);
            $("#fxalert_msg").html(msg);
            if (btntitle == null)
                btntitle = _Language.CommonDialog.DefaultOKBtnTitle;
            $("#fxalert_closebtn").text(btntitle);
            _AlertDlg.dialog('open');
    	}
        
    };

    /**
     * @description Close the Alert dialog.
     */
    FXREADER.EndAlert = function () {
        _AlertDlg && _AlertDlg.dialog('close');
    };

    /**
    * @description Pupup a Confirm dialog.
	* @param {String} title  title of the dialog, if this parameter is null or empty, default title will be use.
	* @param {String} message of the dialog.
	* @param {String} btnOkTitle title of “OK” button, if this parameter is null or empty, default title will be use.
	* @param {String} btnCancelTitle title of “Cancel” button, if this parameter is null or empty, default title will be use.
	* @param {Function} okCallback  callback of user click the “OK” button, if this parameter is null or empty,FXREADER.EndConfirm() will be use by default;
	* @param {Object} okCallbackData parameter of the “okCallback”.
	* @param {Function} cancelCallback  callback of user click the “Cancel” button, if this parameter is null or empty,FXREADER.EndConfirm() will be use by default;
	* @param {Object} cancelCallbackData parameter of the “cancelCallback”.
    */
    FXREADER.Confirm = function (title, msg, btnOkTitle, btnCancelTitle, okCallback, okCallbackData, cancelCallback, cancelCallbackData) {
        _Language = FXREADER.AppInstance.GetLanguage();
        _DefaultDlgTitle = _Language.CommonDialog.DefaultDlgTitle;
        if (!_bComfirmDlgInited) {
            _ConfirmDlgHtml = "<div id='fxconfirm_dialog' title='Confirm' class='fwr_dialog fwr_dialog_padding fwr_hidden'>" +
                                                "<p id='fxconfirm_msg' > </p>" +
                                                "<div class='fwr_buttons_bar_nopadding' id='fxconfirm_btndiv'>" +
                                                    "<button type='button' class='fwr_button orange fwr_dialog_btn_ok'   id='fxconfirm_btok' >" + _Language.CommonDialog.DefaultOKBtnTitle + "</button>" +
                                                    "<button type='button' class='fwr_button blue fwr_dialog_btn_cancel'  id='fxconfirm_btncancel' >" + _Language.CommonDialog.DefaultCancelBtnTitle + "</button>" +
                                                "</div>" +
                                                "<div class='clear'></div>" +
                                            "</div>";
            var jqConfirmDlgHtml = $(_ConfirmDlgHtml);
            _ConfirmDlg = jqConfirmDlgHtml.dialog({
                autoOpen: false,
                modal: true,
                position: 'center',
                minHeight: 38,
                width: 300,
                closeText: '',
                title: _DefaultDlgTitle
            });
            _bComfirmDlgInited = true;
        }
        if (_ConfirmDlg == null)
            return;
        if (title == "" || title == null) {
            title = _DefaultDlgTitle;
        }
        if (msg == null)
            msg = "";
        if (btnOkTitle == null)
            btnOkTitle = _Language.CommonDialog.DefaultOKBtnTitle;
        if (btnCancelTitle == null)
            btnCancelTitle = _Language.CommonDialog.DefaultCancelBtnTitle;
        _ConfirmDlg.dialog("option", "title", title);
        $("#fxconfirm_msg").html(msg);
        $("#fxconfirm_btok").text(btnOkTitle);
        $("#fxconfirm_btncancel").text(btnCancelTitle);
        if (okCallback == null || typeof (okCallback) != "function") {
            okCallback = function () {
                _ConfirmDlg.dialog('close');
            };
        }
        if (cancelCallback == null || typeof (cancelCallback) != "function") {
            cancelCallback = function () {
                _ConfirmDlg.dialog('close');
            };
        }
        $("#fxconfirm_btok").unbind('click').bind('click', function () {
            okCallback(okCallbackData);
        });
        $("#fxconfirm_btncancel").unbind('click').bind('click', function () {
            cancelCallback(cancelCallbackData);
        });

        _ConfirmDlg.dialog("option", "position", 'center');
        _ConfirmDlg.dialog('open');
    };

    /**
     * @description Close the Confirm dialog.
     */
    FXREADER.EndConfirm = function () {
        _ConfirmDlg && _ConfirmDlg.dialog('close');
    };

    FXREADER.ConfirmPassword = function (title, msg, okCallback, btnOkTitle, btnCancelTitle) {
        _Language = FXREADER.AppInstance.GetLanguage();
        _DefaultDlgTitle = _Language.CommonDialog.DefaultDlgTitle;
        var width = 0;
        var minHeight = 200;
        var marginStyle = "margin:10px;text-align: right;";
        var dialogStyle = "max-width: 390px; width:390px; margin-top: 5px; margin-bottom: 5px;";
        var okBtnClass = "fwr_button_wap_ok";
        var cancelBtnClass = "fwr_button_wap_cancel";
        if (FXREADER.Environment.mobile || FXREADER.Environment.iOS) {
        	width = 283;
        	minHeight = 150;
        	dialogStyle = "max-width: 280px; width:280px; margin:0px;margin-bottom: 5px;word-wrap: break-word;word-break: normal;";
        	textAlign = "center";
        	btnsStyle = "text-align: center;margin-top: 20px;";
        	marginStyle = "margin-top:5px;";
        }
        else
        {
        	width = 420;
        	margin = 10;
        	okBtnClass = "fwr_button orange fwr_dialog_btn_ok";
        	cancelBtnClass = "fwr_button blue fwr_dialog_btn_cancel";
        }
        if (!_bConfirmPasswordDlgInited) {
            _ConfirmPasswordDlgHtml = "<div id='fxpsd_dialog' class='fwr_dialog fwr_formEl_a fwr_dlg_main_panel' style='height: 180px;'>" +
                                                            "<div>" +
                                                                "<p id='fxpsd_dialog_msg' style='"+dialogStyle+"'></p>" +
                                                                "<p class='lbl_a'>" + _Language.CommonDialog.EnterPasswordTip + "</p>" +
                                                                "<input class='input inpt_a' type='password' id='fxpsd_dialog_password' name='userpassword' />" +
                                                                "<div style='"+marginStyle+"'>" +
                                                                    "<span id='fxpsd_dialog_FailedInfo' class='deepred'></span>" +
                                                                    "<br />" +
                                                                    "<div style='"+dialogStyle+"'>" +
                                                                        "<button class='"+okBtnClass+"'  id='fxpsd_dialog_btnok' type='button'>" + _Language.CommonDialog.DefaultOKBtnTitle + "</button>" +
                                                                        "<button class='"+cancelBtnClass+"'  id='fxpsd_dialog_btncancel' type='button'>" + _Language.CommonDialog.DefaultCancelBtnTitle + "</button>" +
                                                                    "</div>" +
                                                                "</div>" +
                                                            "</div>" +
                                                        "</div>";
            var jqPsdConfirmDlgHtml = $(_ConfirmPasswordDlgHtml);
            _ConfirmPasswordDlg = jqPsdConfirmDlgHtml.dialog({
                autoOpen: false,
                modal: true,
                position: 'center',
                closeText: '',
                minHeight: minHeight,
                width: width,
                title: _DefaultDlgTitle,
                open: function () {
                    // scrollbar fix for IE
                	var parent = $("#fxpsd_dialog").parent();
                	parent.css('z-index', "1005");
                },
                beforeClose: function()
                {
                	 $('.ui-widget-overlay').css('background-color', "#000");
                	 $('.ui-widget-overlay').css('z-index', "1003");
                	 $('.fwr_main_frame_wnd').css('z-index', "1001");
                },
                close: function () {
                }
               
            });
            $("#fxpsd_dialog_password").unbind('keyup').bind('keyup', function (event) {
                var theEvent = event || window.event;
                var code = theEvent.keyCode || theEvent.which || theEvent.charCode; //获取键盘code
                if (code == '13') {
                    //document.getElementById("fxpsd_dialog_btnok").click();
                    $("#fxpsd_dialog_btnok").click();
                }
            });
            $("#fxpsd_dialog_btncancel").unbind('click').bind('click', function () {
                _ConfirmPasswordDlg.dialog('close');
            });
            _bConfirmPasswordDlgInited = true;
        }
        if (_ConfirmPasswordDlg == null)
            return;

        $("#fxpsd_dialog_password").empty();
        $("#fxpsd_dialog_FailedInfo").empty();
        if (title == "" || title == null) {
            title = _DefaultDlgTitle;
        }
        if (msg == null)
            msg = "";
        if (btnOkTitle == null)
            btnOkTitle = _Language.CommonDialog.DefaultOKBtnTitle;
        if (btnCancelTitle == null)
            btnCancelTitle = _Language.CommonDialog.DefaultCancelBtnTitle;
        _ConfirmPasswordDlg.dialog("option", "title", title);
        $("#fxpsd_dialog_msg").html(msg);
        $("#fxpsd_dialog_btnok").text(btnOkTitle);
        $("#fxpsd_dialog_btncancel").text(btnCancelTitle);
        if (okCallback == null || typeof (okCallback) != "function") {
            okCallback = function () {
                _ConfirmPasswordDlg.dialog('close');
            };
        }
        $("#fxpsd_dialog_btnok").unbind('click').bind('click', function () {
            okCallback($("#fxpsd_dialog_password"), $("#fxpsd_dialog_FailedInfo"));
        });
        _ConfirmPasswordDlg.dialog("option", "position", 'center');
        _ConfirmPasswordDlg.dialog('open');
        $("#fxpsd_dialog_password").focus();
    };


    FXREADER.EndConfirmPassword = function () {
        _ConfirmPasswordDlg && $("#fxpsd_dialog_password").empty();
        _ConfirmPasswordDlg && $("#fxpsd_dialog_password").val("");
        _ConfirmPasswordDlg && _ConfirmPasswordDlg.dialog('close');
    }


    function _ClipboardfromFirefox(text) {
        if (window.netscape) {   //Firefox浏览器
            try {
                netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
            }
            catch (e) {

                return false;
            }
            var clip = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard);
            if (!clip) return;
            var trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable);
            if (!trans) return;
            trans.addDataFlavor('text/unicode');
            var str = new Object();
            var len = new Object();
            var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
            var copytext = text; str.data = copytext;
            trans.setTransferData("text/unicode", str, copytext.length * 2);
            var clipid = Components.interfaces.nsIClipboard;
            if (!clip) return false;
            clip.setData(trans, null, clipid.kGlobalClipboard);

            return true;
        }
    }

    FXREADER.CopyText = function (text2Copy, title, btntitle, closeProc, width) {
        try {
            if (window.clipboardData) {
                var bClip = window.clipboardData.setData("Text", text2Copy);
                if (!bClip) {
                    _PopupCopyDlg(text2Copy, title, btntitle, closeProc, width);
                    return false;
                }
            }
            else if (window.netscape) {
                if (!_ClipboardfromFirefox(text2Copy)) {
                    _PopupCopyDlg(text2Copy, title, btntitle, closeProc, width);
                    return false;
                }
            }
            else {
                _PopupCopyDlg(text2Copy, title, btntitle, closeProc, width);
                return false;
            }
        }
        catch (err) {
            _PopupCopyDlg(text2Copy, title, btntitle, closeProc, width);
            return false;
        }
        return true;
    };

    FXREADER.EndTextCopyDlg = function () {
        _TextCopyDlg && _TextCopyDlg.dialog('close');
    };
});
